<template>
<div class="container">
    <div class="login-container">
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on"
               label-position="left">

        <div class="title-container">
          <h3 class="title">登录</h3>
        </div>

        <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user"/>
        </span>
          <el-input
            ref="username"
            v-model="loginForm.username"
            placeholder="Username"
            name="username"
            type="text"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>

        <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password"/>
        </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="Password"
            name="password"
            tabindex="2"
            auto-complete="on"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"/>
        </span>
        </el-form-item>

        <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;"
                   @click.native.prevent="handleLogin">Login
        </el-button>
        <el-row style="text-align: right; margin-top: -20px;;">
          <el-link type="primary" @click="showCardDialog()">用户注册</el-link>
        </el-row>
      </el-form>
    </div>
  <div>
  <el-dialog align="center" title="用户注册" :visible.sync="cardDialogVisible" width="858px"
             @close="closeDialog()">
    <!-- 内容主体 -->
    <div>
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
        <el-row type="flex" justify="center" align="top">
          <el-col :span="15">
            <el-form-item label="头像" prop="picture">
              <el-upload
                ref="upload"
                class="avatar-uploader"
                action="http://127.0.0.1:8080/network/user/uploadImg"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <div slot="tip" class="el-upload__tip">只能上传图片类型文件，且不超过2MB</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center" align="top">
          <el-col :span="15">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name" placeholder="请输入真实姓名" :maxlength="20" show-word-limit
                        clearable prefix-icon='el-icon-s-custom' :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center" align="top">
          <el-col :span="15">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="formData.gender" size="medium">
                <el-radio v-for="(item, index) in genderOptions" :key="index" :label="item.value"
                          :disabled="item.disabled">{{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center" align="top">
          <el-col :span="15">
            <el-form-item label="昵称" prop="nickName">
              <el-input v-model="formData.nickName" placeholder="请输入昵称" :maxlength="20" show-word-limit
                        clearable prefix-icon='el-icon-s-custom' :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center" align="top">
          <el-col :span="15">
            <el-form-item label="密码" prop="password">
              <el-input v-model="formData.password" type="password" placeholder="请输入新密码" :maxlength="20" show-word-limit
                        clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center" align="top">
          <el-col :span="15">
            <el-form-item label="确认密码" prop="checkPass">
              <el-input v-model="formData.checkPass" type="password" placeholder="请再次输入新密码" :maxlength="20" show-word-limit
                        clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center" align="top">
          <el-col :span="15">
            <el-form-item label="职业" prop="profession">
              <el-input v-model="formData.profession" placeholder="请输入职业" :maxlength="20" show-word-limit
                        clearable prefix-icon='el-icon-monitor' :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center" align="top">
          <el-col :span="15">
            <el-form-item label="所属省市：" prop="province">
              <el-select style="width: 50%" v-model="formData.province" placeholder="请选择省份（直辖市）"
                         @change="renderCity"
                         clearable>
                <el-option
                  v-for="item in provinceListAll"
                  :key="item.name"
                  :value="item.name">
                </el-option>
              </el-select>
              <el-select style="width: 50%" v-model="formData.city" placeholder="请选择城市" v-if="citySelectAble"
                         clearable>
                <el-option
                  v-for="item in cityListAll"
                  :key="item.name"
                  :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center" align="top">
          <el-col :span="15">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker v-model="formData.birthday" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                              :style="{width: '100%'}" placeholder="请选择生日" clearable></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center" align="top">
          <el-col :span="15">
            <el-form-item label="手机" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入手机号" :maxlength="11" show-word-limit clearable
                        prefix-icon='el-icon-mobile' :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center" align="top">
          <el-col :span="15">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" placeholder="请输入邮箱" :maxlength="30" show-word-limit
                        clearable prefix-icon='el-icon-folder' :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center" align="top">
          <el-col :span="15">
            <el-form-item label="个性签名" prop="signature">
              <el-input v-model="formData.signature" type="textarea" placeholder="请输入个性签名"
                        :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center" align="top">
          <el-col :span="15">
            <el-form-item size="large">
              <el-button type="primary" @click="submitForm"> 提交</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </el-dialog>
  </div>
</div>


</template>

<script>
  import {validUsername} from '@/utils/validate'
  import {getInfo} from "@/api/user";
  import request from "@/utils/request";

  export default {
    name: 'Login',
    data() {
      const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入新密码'));
        } else {
          callback();
        }
      };
      const validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入新密码'));
        } else if (value !== this.formData.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      const validateUsername = (rule, value, callback) => {
        if (!validUsername(value)) {
          callback(new Error('请输入正确账号或昵称'))
        } else {
          callback()
        }
      }
      const validatePassword = (rule, value, callback) => {
        if (value.length < 6) {
          callback(new Error('密码不得少于6位'))
        } else {
          callback()
        }
      }
      return {
        cardDialogVisible: false,
        imageUrl: '',
        formData: {
          nickName: '',
          avatar: '',
          profession: '',
          province: '',  // 所属省（直辖市）
          city: '',
          gender: 1,
          birthday: null,
          phone: '',
          email: '',
          signature: '',
          submit: '',
          reset: '',
          password: '',
          checkPass: ''
        },
        mapApiKey: 'dc29f1c38025b144fd39e742bb45bb0b',
        provinceListAll: [],      // 全国34个省份（包括直辖市）列表
        cityListAll: [],        // 全国各个城市列表
        citySelectAble: false,    // 城市是否可选
        rules: {
          nickName: [{
            required: true,
            message: '请输入昵称',
            trigger: 'blur'
          }],
          name: [{
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }],
          password: [
            { required: true, validator: validatePass, trigger: 'blur' }
          ],
          checkPass: [
            { required: true, validator: validatePass2, trigger: 'blur' }
          ],
          profession: [{
            required: true,
            message: '请输入职业',
            trigger: 'blur'
          }],
          province: [{
            required: true,
            message: '请输入所属省份（或者直辖市）',
            trigger: 'blur'
          }],
          gender: [{
            required: true,
            message: '性别不能为空',
            trigger: 'change'
          }],
          birthday: [{
            required: true,
            message: '请选择生日',
            trigger: 'change'
          }],
          phone: [{
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          }, {
            pattern: /^1(3|4|5|7|8|9)\d{9}$/,
            message: '手机号格式错误',
            trigger: 'blur'
          }],
          email: [{
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          }],
          signature: [{
            message: '请输入个性签名',
            trigger: 'blur'
          }],
        },
        genderOptions: [{
          "label": "男",
          "value": 1
        }, {
          "label": "女",
          "value": 0
        }],

        loginForm: {
          username: 'zhangsan',
          password: '123456'
        },
        loginRules: {
          username: [{required: true, trigger: 'blur', validator: validateUsername}],
          password: [{required: true, trigger: 'blur', validator: validatePassword}]
        },
        loading: false,
        passwordType: 'password',
        redirect: undefined
      }
    },
    watch: {
      $route: {
        handler: function (route) {
          this.redirect = route.query && route.query.redirect
        },
        immediate: true
      }
    },
    methods: {
      getAllProvinceAndCityList() {     // 获取全国所有省份和城市的列表
        var that = this;
        this.$http.get('https://restapi.amap.com/v3/config/district', {   // 高德地图的API
          params: {
            key: this.mapApiKey,   // 这个是申请的 Key
            keywords: '中国',
            subdistrict: 3,
            extensions: 'base'
          }
        }).then((response) => {
          that.provinceListAll = response.data.districts[0].districts;
          for (let i = 0; i < response.data.districts[0].districts.length; i++) {
            for (let j = 0; j < response.data.districts[0].districts[i].districts.length; j++) {
              that.cityListAll.push(response.data.districts[0].districts[i].districts[j]);
            }
          }
          // console.log('省份',that.provinceListAll);
          // console.log('城市',that.cityListAll);
        });
      },

      renderCity() {    // 根据选择的省份，展示该省份相对应的城市列表，未选择省份时，不能选择城市
        this.citySelectAble = false;
        if ((this.formData.province.length > 0) && (this.formData.city)) {
          this.formData.city = '';
        }
        if (this.formData.province.length > 0) {
          this.cityListAll = this.provinceListAll.filter(item => item.name == this.formData.province)[0].districts;
          this.citySelectAble = true;
        } else if (!this.formData.province) {
          this.citySelectAble = false;
          this.formData.city = '';     // 清空省份选择时，清空之前选择的城市能进行重新选择城市
        }
      },

      // 显示对话框
      showCardDialog() {

        this.getAllProvinceAndCityList()
        this.cardDialogVisible = true
      },
      closeDialog() {
        this.formData = {}
        this.cardDialogVisible = false
      },
      submitForm() {
        this.$refs['elForm'].validate(valid => {
          console.log(this.formData)
          if (!valid) return this.$message.error("表单校验失败")
          const params = this.formData
          request({
            url: '/user/register',
            method: 'get',
            params
          }).then(response => {
            console.log("发送请求")
            console.log(response.retCode)
            if (response.retCode !== '200') return this.$message.error(response.retMsg)
            this.$message.success('注册成功！')
            this.cardDialogVisible = false
          })
        })
      },
      resetForm() {
        this.$refs['elForm'].resetFields()
      },


      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        this.formData.avatar = res;
      },
      beforeAvatarUpload(file) {
        let isRightSize = file.size / 1024 / 1024 < 2
        if (!isRightSize) {
          this.$message.error('文件大小超过 2MB')
        }
        let isAccept = new RegExp('image/*').test(file.type)
        if (!isAccept) {
          this.$message.error('应该选择图片类型的文件')
        }
        return isRightSize && isAccept

      },
      showPwd() {
        if (this.passwordType === 'password') {
          this.passwordType = ''
        } else {
          this.passwordType = 'password'
        }
        this.$nextTick(() => {
          this.$refs.password.focus()
        })
      },
      handleLogin() {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true
            this.$store.dispatch('user/login', this.loginForm).then(() => {
              this.$router.push({path: this.redirect || '/'})
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    }
  }
</script>

<style lang="scss">
  /* 修复input 背景不协调 和光标变色 */
  /* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

  $bg: #283443;
  $light_gray: #fff;
  $cursor: #fff;

  @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
    .login-container .el-input input {
      color: $cursor;
    }
  }

  .container {
    min-height: 100%;
    width: 100%;
    background-color: $bg;

  }

  /* reset element-ui css */
  .login-container {
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;

      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: $light_gray;
        height: 47px;
        caret-color: $cursor;

        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px $bg inset !important;
          -webkit-text-fill-color: $cursor !important;
        }
      }
    }

    .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 1000px;
    margin-left: 80px;
  }
</style>

<style lang="scss" scoped>
  $bg: #2d3a4b;
  $dark_gray: #889aa4;
  $light_gray: #eee;

  .login-container {
    min-height: 100%;
    width: 100%;
    background-color: $bg;
    overflow: hidden;

    .login-form {
      position: relative;
      width: 520px;
      max-width: 100%;
      padding: 160px 35px 0;
      margin: 0 auto;
      overflow: hidden;
    }

    .tips {
      font-size: 14px;
      color: #fff;
      margin-bottom: 10px;

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      color: $dark_gray;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }

    .title-container {
      position: relative;

      .title {
        font-size: 26px;
        color: $light_gray;
        margin: 0px auto 40px auto;
        text-align: center;
        font-weight: bold;
      }
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }
  }

  .container {
    min-height: 100%;
    width: 100%;
    background-color: $bg;
    overflow: hidden;
  }




</style>
